package com.atguigu.admin.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author Chen Yaqi
 * @version 1.0
 */
@Controller
@Slf4j
public class FormController {
    @GetMapping("/form_layouts")
    public String formLayouts(Model model) {
        model.addAttribute("active","forms");
        model.addAttribute("flag","formLayouts");
        return "form/form_layouts";
    }

    @PostMapping("/upload")
    public String upload(@RequestParam("email") String email,
                         @RequestParam("username") String username,
                         @RequestPart("headerImg") MultipartFile headerImg,
                         @RequestPart("photos") MultipartFile[] photos) {
        log.info("上传的信息：email={},username={},headerImg={},photos={}", email, username, headerImg.getSize(), photos.length);

        if (!headerImg.isEmpty()){
            // 保存到文件系统，OSS服务器
            String originalFilename = headerImg.getOriginalFilename();
            //处理文件重名问题
            String hzName = originalFilename.substring(originalFilename.lastIndexOf("."));
            originalFilename = UUID.randomUUID().toString() + hzName;
            try {
                File file = new File("D:\\tempFile");
                if (!file.exists()){
                    file.mkdir();
                }
                headerImg.transferTo(new File("D:\\tempFile\\" + originalFilename));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "redirect:/form_layouts";
    }
}
